﻿using System;
using GeoAPI.Geometries;

namespace NetTopologySuite.Index.Quadtree
{
	public class Key
	{
		public static int ComputeQuadLevel(Envelope env)
		{
			double width = env.Width;
			double height = env.Height;
			return DoubleBits.GetExponent((width > height) ? width : height) + 1;
		}

		public Key(Envelope itemEnv)
		{
			this.ComputeKey(itemEnv);
		}

		public Coordinate Point
		{
			get
			{
				return this._pt;
			}
		}

		public int Level
		{
			get
			{
				return this._level;
			}
		}

		public Envelope Envelope
		{
			get
			{
				return this._env;
			}
		}

		public Coordinate Centre
		{
			get
			{
				return new Coordinate((this._env.MinX + this._env.MaxX) / 2.0, (this._env.MinY + this._env.MaxY) / 2.0);
			}
		}

		public void ComputeKey(Envelope itemEnv)
		{
			this._level = Key.ComputeQuadLevel(itemEnv);
			this._env = new Envelope();
			this.ComputeKey(this._level, itemEnv);
			while (!this._env.Contains(itemEnv))
			{
				this._level++;
				this.ComputeKey(this._level, itemEnv);
			}
		}

		private void ComputeKey(int level, Envelope itemEnv)
		{
			double num = DoubleBits.PowerOf2(level);
			this._pt.X = Math.Floor(itemEnv.MinX / num) * num;
			this._pt.Y = Math.Floor(itemEnv.MinY / num) * num;
			this._env.Init(this._pt.X, this._pt.X + num, this._pt.Y, this._pt.Y + num);
		}

		private readonly Coordinate _pt = new Coordinate();

		private int _level;

		private Envelope _env;
	}
}
